#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
using namespace std;

#define SIZE 1024
#define MAX_SIZE 64
#define SEP " "

char* argv[MAX_SIZE];
char pwd[SIZE];

const char* HostName()
{
    char* hostname = getenv("HOSTNAME");
    if (hostname) 
        return hostname;
    else
        return "None";
}
const char* UserName()
{
    char* username = getenv("USER");
    if (username) 
        return username;
    else
        return "None";
}
const char* WorkDir()
{
    char* workdir = getenv("PWD");
    if (workdir)
        return workdir;
    else 
        return "None";
}

void Interact(char* out, int size)
{
    // 输出命令行提示符并获取用户输入的命令字符串
    fprintf(stdout, "[%s@%s %s]$ ", UserName(), HostName(), WorkDir());
    fgets(out, size, stdin);
    out[strlen(out) - 1] = NULL; // fgets也会把'\n'字符存储，这里去掉此多余字符
}

void Split(char* in)
{
    int i = 0;
    //strtok 对输入的字符串指令进行切割
    argv[i++] = strtok(in, SEP);
    while (argv[i++] = strtok(NULL, SEP))
    {   }
}

void Execute()
{
    pid_t id = fork();
    if (id == 0)
    {
        execvp(argv[0], argv);
        exit(1);
    }
    waitpid(id, NULL, 0);
}

int BuildCommand()
{
    //1, 检测输入的指令程序是否是内建指令，1表示是，0表示不是
    
}

int main()
{
    //1, 输出命令行提示符并获取用户输入的命令字符串
    char commandline[SIZE]; 
    Interact(commandline, SIZE);
    //2, 对命令行字符串进行切割
    Split(commandline);
    //3, 处理内建命令
    int check = BuildCommand(); 
    if (check) continue;
    //4, 开始执行输入的程序指令
    Execute();
    return 0;
}
